define(function(require,exports,module) {
    var myPub = require('./public');

    var oWindow = $(window);
    var oOrderSearchArea = $('.js_orderSearchArea');                // 我的订单页搜索入口
    var oSlideSearchBox = $('.js_slideSearchBox');                  // 侧滑的搜索页面
    var nSildeWidth = oSlideSearchBox.outerWidth(true);             // 整个侧边搜索区域的宽度
    var lazLoading = new myPub.lazLoadingImg();
    var isInit = true;                                              // 获取节点
    var bSearch = false;                                            // 是否展示搜索页
    var searchWord = '';                                            // 搜索的关键字
    var resizeTimer = null;
    // 搜索数据路径
    var searchUrl = '/m/o/1.0/order/mySearch';
    var storeDetailUrl = '/m/g/supplier/1.0/isOverSeaSupplier';        // 判断是进入海外店铺还是进入普通店铺的接口

    // 搜索列表
    var searchOrder = {
        oNoOrder: '',
        oSlideSearchArea: '',
        oSlideSearchCancel: '',
        oSlideOrder: '',
        nSlideSearchHeight: '',
        oSlideSearchText: '',
        oSearchOrederList: '',
        oClearSearchBtn: '',
        oHasSearchData: '',
        oMoreBtnBox: '',

        limit: 10,                      // 每次加载多少数据
        getData: [],                    // 数据记录
        pagearr: 1,                     // 当前页码
        start:0,                        // 开始数据
        bLoadOff: true,                 // 加载开关
        bScrollLoadOff: true,           // 滚动加载开关
        scroll_timer: null,             // 滚动定时器

        // 初始化
        init:function () {
            var _this = this;
            _this.oSlideSearchArea = $('.js_slideSearchArea');                      // 搜索区域
            _this.oSlideSearchText = $('.js_slideSearchText');                      // 输入框
            _this.oClearSearchBtn = $('.js_clearSearchBtn');                        // 清空输入框按钮
            _this.oSlideSearchCancel = $('.js_slideSearchCancel');                  // 取消按钮
            _this.oSlideOrder = $('.js_slideOrder');                                // 显示订单区域
            _this.oHasSearchData = $('.js_hasSearhData');                           // 有数据时显示内容
            _this.oNoOrder = $('.js_noOrder');                                      // 没有订单的页面
            _this.oSearchOrederList = $('.js_searchOrederList');                    // 搜索到的订单区域
            _this.oMoreBtnBox = $('.js_moreBtnBox');                                // 没有更多了或者加载中的按钮
            _this.nSlideSearchHeight = _this.oSlideSearchArea.outerHeight(true);    // 顶部搜索区域的高度

            oSlideSearchBox.css({'left': ( nSildeWidth+10 )+'px'});                 // 侧边搜索栏是否显示

            _this.oSlideOrder.css({
                'height': oWindow.height() - _this.nSlideSearchHeight,
                'padding-top': _this.nSlideSearchHeight
            });

            // 取消按钮
            _this.oSlideSearchCancel.on('click',function (e) {
                bSearch = false;
                oSlideSearchBox.stop().animate({left:( nSildeWidth+10 )+'px'},300,function(){
                    oSlideSearchBox.hide();
                    // 清空数据
                    /*searchOrder.oSlideSearchText.val('');
                    searchOrder.oSearchOrederList.html('');
                    searchOrder.oMoreBtnBox.hide();
                    searchOrder.oClearSearchBtn.hide();

                    // 显示有数据页面
                    searchOrder.oNoOrder.hide();
                    searchOrder.oHasSearchData.show();

                    searchOrder.pagearr = 1;
                    searchOrder.start = 0;*/
                });
                e.stopPropagation();
            });
        },

        // 检测输入框
        getInputData:function(){
            var _this = this;
            // 输入是显示隐藏清空按钮
            _this.oSlideSearchText.on('input propertychange',function () {
                var searchVal = _this.oSlideSearchText.val();
                if(searchVal.length > 0){
                    _this.oClearSearchBtn.show();
                }else{
                    _this.oClearSearchBtn.hide();
                }
            });

            // 获取焦点时显示隐藏清空按钮
            _this.oSlideSearchText.on('focus', function () {
                var searchVal = _this.oSlideSearchText.val();
                if(searchVal.length > 0){
                    _this.oClearSearchBtn.show();
                }else{
                    _this.oClearSearchBtn.hide();
                }
            });

            // 点击清空按钮清空输入框
            _this.oClearSearchBtn.on('click',function (e) {
                _this.oSlideSearchText.val('');
                e.stopPropagation();
            })

        },

        // 获取数据
        getSearchData: function (keyWord) {
            var _this = this;
            G_JSON_POST(searchUrl, {
                'keyword': keyWord,
                'start': _this.start,
                'limit': _this.limit
            },function (data) {
                var dataItem = data;
                if(dataItem.ret.code == '0'){
                    if(dataItem.data == null && _this.pagearr < 2){
                        // 关闭滚动加载
                        _this.bScrollLoadOff = false;
                        // 显示没有数据页面
                        _this.oNoOrder.show();
                        _this.oHasSearchData.hide();
                        return
                    }
                    if(dataItem.data == null && _this.pagearr > 1){
                        // 关闭滚动加载
                        _this.bScrollLoadOff = false;
                        // 显示没有更多了
                        _this.oMoreBtnBox.find('.js_loadingBtn').eq(1).hide();
                        _this.oMoreBtnBox.find('.js_loadingBtn').eq(0).show();
                        return
                    }
                    _this.getSearchHtml(dataItem.data);
                    if(dataItem.data && dataItem.data.length < _this.limit){
                        // 关闭滚动加载
                        _this.bScrollLoadOff = false;
                        // 显示没有更多了
                        _this.oMoreBtnBox.find('.js_loadingBtn').eq(1).hide();
                        _this.oMoreBtnBox.find('.js_loadingBtn').eq(0).show();
                    }

                }else{
                    // 关闭滚动加载
                    _this.bScrollLoadOff = false;
                    // 显示没有数据页面
                    _this.oNoOrder.show();
                    _this.oHasSearchData.hide();
                }
            })
        },

        // 滚动加载
        scrollData: function(){
            var _this = this;
            var minHeight = 200;                 // 滚动到离底部的距离然后加载数据
            _this.oSlideOrder.off('scroll');
            _this.oSlideOrder.on('scroll',function () {
                var afterScroll = $(this).scrollTop();
                clearTimeout(_this.scroll_timer);
                _this.scroll_timer = setTimeout(function () {
                    if(_this.oSlideOrder[0].scrollHeight - afterScroll - _this.oSlideOrder.height() < minHeight){
                        if(_this.bScrollLoadOff){
                            _this.start = _this.limit*_this.pagearr;
                            _this.pagearr++;
                            _this.getSearchData(searchWord);
                        }
                    }
                },200)
            });
        },
        
        // 拼接订单
        getSearchHtml: function (orderArr) {
            var _this = this;
            var UlHtml = '';
            var tHtml = '';
            for(var i = 0;i < orderArr.length; i++){
                var arrItem = orderArr[i];
                var multiGiftClass = "";
                tHtml = '';

                // 商品  部分
                var href = BASE_URL + '/shop/pay/order_view?orderSn=' + arrItem.orderSn + '&orderStatus=' + arrItem.orderStatus;
                if( arrItem.giftOrderShowType == '2'){
                    multiGiftClass = "backWhite moreSendGift";
                    href = "/shop/gift/multiGiftOrderEntryDetail?paymentOrderId=" + arrItem.paymentOrderId;
                }
                for(var j = 0; j < arrItem.orderItemVOList.length; j++){
                    var goodsItem = arrItem.orderItemVOList[j];
                    var productNameAreaHtml;
                    var productPriceAreaHtml;
                    var shareTaHtml;
                    if( arrItem.giftOrderShowType == '2' ){
                        var remainSecond = parseInt(arrItem.remainSecond);
                        productPriceAreaHtml  = [
                            '           <div class="priceArea_price HBox">',
                            '               <p class="priceAreaBox Bflex1"><span class="goodsPriceOld">￥' + goodsItem.productPrice + '</span></p>',
                            '           </div>'].join("");
                        if(remainSecond>0){
                            productNameAreaHtml = [
                                '<div class="Bflex1 priceArea_name">',
                                '<h4>' + goodsItem.goodsName + '</h4>',
                                '<p class="smallFont_tip">',
                                '<span>剩余'+arrItem.giftRemainQty+'个未领取</span>',
                                '<span>/</span>',
                                '<span>共'+arrItem.giftTotalQty+'个</span>',
                                '</p>',
                                '</div>'].join("");
                            if (arrItem.giftRemainQty > 0){
                                shareTaHtml = '<p class="shareTABtn"><a href="/shop/gift/sharePage/'+arrItem.paymentOrderId+'" class="btnStyle btn_BorderGray">分享给Ta</a></p>';
                            }

                            // shareTaHtml = '<button class="redBtn" type="button" _type="7" oid="' + order.paymentOrderId + '">分享给TA</button>';
                        }else{
                            if(arrItem.giftRemainQty>0){
                                productNameAreaHtml = [
                                    '<div class="Bflex1 priceArea_name">',
                                    '<h4>' + goodsItem.goodsName + '</h4>',
                                    '<p class="smallFont_tip">',
                                    '<span>剩余'+arrItem.giftRemainQty+'个未领取已退款</span>',
                                    '</p>',
                                    '</div>'].join("");
                            }else{
                                productNameAreaHtml = [
                                    '<div class="Bflex1 priceArea_name">',
                                    '<h4>' + goodsItem.goodsName + '</h4>',
                                    '<p class="smallFont_tip">',
                                    '<span>已抢光</span>',
                                    '</p>',
                                    '</div>'].join("");
                            }
                            shareTaHtml = '<p class="shareTABtn"><a href="/shop/gift/multiGiftOrderEntryDetail?paymentOrderId='+arrItem.paymentOrderId+'" class="btnStyle btn_BorderGray">查看详情</a></p>';
                        }
                    }else{
                        var jifenHtml = '';
                        if(goodsItem.isJifen != false){
                            if(goodsItem.productPrice == 0){
                                jifenHtml = '<p class="priceAreaBox Bflex1"><span class="goodsPriceOld">￥'+ goodsItem.memberPoint+'积分'+'</span></p>';
                            }else{
                                jifenHtml = '<p class="priceAreaBox Bflex1"><span class="goodsPriceOld">￥' + goodsItem.productPrice + '+'+ goodsItem.memberPoint+'积分'+'</span></p>';
                            }
                        }else{
                            jifenHtml = '<p class="priceAreaBox Bflex1"><span class="goodsPriceOld">￥' + goodsItem.productPrice + '</span></p>';
                        }
                        productNameAreaHtml =
                            ['           <div class="Bflex1 priceArea_name">',
                                '               <h4>' + goodsItem.goodsName + '</h4>',
                                '               <p class="smallFont_tip"><span>规格:</span><span>已选择' + goodsItem.productName + '</span></p>',
                                '           </div>'].join("");
                        productPriceAreaHtml =
                            ['           <div class="priceArea_price HBox">',
                                                jifenHtml,
                                '               <p class="selProNum">' +
                                '                   <span>×</span><span class="proNumber">' + goodsItem.quantity + '</span>' +
                                '               </p>',
                                '             </div>'].join("");
                        shareTaHtml = "";
                    }
                    tHtml += [
                        '<li>' +
                        '   <a class="BoxSelf" href="' + href + '">',
                        '       <figure>',
                        '           <img class="js_lazyImg fadeIn" data-echo="' + HTTP_IMAGE_URL + goodsItem.goodsImage + smallImgArg200 +'" src="' + BASE_URL + '/static_v4/image/loadImg.jpg">',
                        '       </figure>',
                        '       <aside class="priceArea VBox Bflex1">',
                                    productNameAreaHtml,
                                    productPriceAreaHtml,
                        '       </aside>',
                        '   </a>',
                            shareTaHtml,
                        '</li>'].join("");
                }

                // 获取订单合并的头部 未付款的订单按照购物车合并 其他的按照 商家合并
                var orderGroupHtml;
                if( arrItem.giftOrderShowType != '0'){
                    orderGroupHtml = [  '<a class="js_goToStore" data-supplierId="'+arrItem.supplierId+'">',
                        '   <span class="tip_sendGift">送礼</span>',
                        '   <span class="icon_store iconStyle"></span>',
                        '   <span class="orderShopName">' + arrItem.supplierName + '</span>',
                        '</a>'].join("");
                }else {
                    orderGroupHtml = [  '<a  class="js_goToStore" data-supplierId="'+arrItem.supplierId+'">',
                        '   <span class="icon_store iconStyle"></span>',
                        '   <span class="orderShopName">' + arrItem.supplierName + '</span>',
                        '</a>'].join("");
                }

                // 订单类型
                var orderStatusText;
                if( arrItem.giftOrderShowType == '2' ){
                    var remainSecond = parseInt(arrItem.remainSecond);
                    if( remainSecond>0 && arrItem.giftRemainQty > 0 ){
                        orderStatusText = '距订单关闭还剩 <span class="jsAddressTimer" data-timer="' + remainSecond + '"></span>';
                    }else if( remainSecond>0 && arrItem.giftRemainQty == 0 ){
                        orderStatusText = '<span>待发货</span>';
                    } else{
                        orderStatusText = '<span>'+arrItem.giftOrderStatusStr+'</span>';
                    }
                }else{
                    switch (arrItem.orderStatus){
                        case 'PAYFINISH' : orderStatusText = '待发货';break;
                        case 'SHIPPED' : orderStatusText = '待收货';break;
                        case 'FINISHED' : orderStatusText = '交易完成';break;
                        case 'WAITING_FILL_ADDR' :
                            var remainSecond = parseInt(arrItem.remainSecond);
                            orderStatusText = '待TA填地址 <span class="jsAddressTimer" data-timer="' + remainSecond + '"></span>';
                            break;
                        case 'CANCEL' :
                        case 'OVERTIME' :
                        case 'CLOSEED' :
                            orderStatusText = '交易关闭';break;
                    }
                }

                // 订单底部按钮
                var totalAmount = arrItem.paidAmount;
                var orderBtn;
                orderBtn = '<div class="transacSuccBtn orderAllBtn HBox">';
                orderBtn += '<div class="Bflex1"></div>';
                if('FINISHED' == arrItem.orderStatus || 'OVERTIME' == arrItem.orderStatus || 'CLOSEED' == arrItem.orderStatus){
                    orderBtn += '<button class="" type="button" _type="0" oid="' + arrItem.id + '">删除订单</button>';
                }
                if('WAITING_FILL_ADDR' == arrItem.orderStatus){
                    orderBtn += '<button class="redBtn" type="button" _type="7" oid="' + arrItem.paymentOrderId + '">分享给TA</button>';
                }
                if('PAYFINISH' == arrItem.orderStatus){
                    orderBtn += '<button type="button" _type="1" oid="' + arrItem.id + '">提醒发货</button>';
                }
                if( arrItem.giftOrderShowType != '1' && ('SHIPPED' == arrItem.orderStatus || 'FINISHED' == arrItem.orderStatus)){
                    orderBtn += '<button class="" type="button" _type="2" oid="' + arrItem.id + '" _orderSn="'+arrItem.orderSn+'">查看物流</button>';
                }
                if('SHIPPED' == arrItem.orderStatus){
                    orderBtn += '<button class="redBtn" type="button" _type="3" oid="' + arrItem.id + '">确认收货</button>';
                }
                if('FINISHED' == arrItem.orderStatus){
                    // console.log("ces1 ++++"+orderArr[0].isGgoodsComment);
                    if (arrItem.isGoodsComment == "1"){
                        orderBtn += '<button class="redBtn" type="button" _type="4" oid="' + arrItem.id + '" >评价有礼</button>';
                    }else if (arrItem.isGoodsComment == "2"){
                        // console.log("ces2 ++++"+orderArr[0].isGgoodsComment);
                        orderBtn += '<button class="redBtn" type="button" _type="8" oid="' + arrItem.id + '">追加评价</button>';
                    }else  if (arrItem.isGoodsComment == "3"){
                        //已经追评
                        // console.log("ces3 ++++"+orderArr[0].isGgoodsComment);
                    }
                }
                orderBtn += '</div>';

                var orderFooterHtml;
                if(arrItem.giftOrderShowType == '2'){//不用显示
                    orderFooterHtml = "";
                }else{
                    var receiverHtml;
                    if(arrItem.giftOrderShowType == '1' && arrItem.giftRemainQty != '1'){
                        receiverHtml ='<div class="getGiftUser"><span>领取者：'+arrItem.giftReceiver+'</span></div>';
                    }else{
                        receiverHtml = '';
                    }
                    orderFooterHtml = ['<div class="onOrderFoot">',
                        '           <div class="seletPrice borBEA HBox">',
                                        receiverHtml,
                        '               <p class="Bflex1">',
                        '                   <span class="selPriLeft">共<i>' + arrItem.quantity + '</i>件商品</span>',
                        '                   <span class="selPriTotal">小计：<em>￥</em><span class="sumPrice">' + totalAmount.toFixed(2) +'</span></span>',
                        '               </p>',
                        '           </div>',
                        '           <div class="orderBtnBox">',
                                        orderBtn,
                        '           </div>',
                        '       </div>'].join("");
                }

                UlHtml +=
                    '<li>'+
                    '   <div class="transactionSuc '+multiGiftClass+'">'+
                    '       <div class="myOrderTranT backWhite">'+
                    '           <div class="myOrderShop myFlex myBetween borBEA">'+
                    '               <div class="myOrderShopL colTT HBox">'+
                                        orderGroupHtml+
                    '               </div>'+
                    '               <div class="myOrderShopR myFlex colFT">'+
                    '                   <span>'+orderStatusText+'</span>'+
                    '               </div>'+
                    '           </div>'+
                    '           <div class="orderProduction goods_showChangeBox">'+
                    '               <div class="goods_showChange">'+
                    '                   <ul class="goodsList clearfix js_goodsList">'+
                                           tHtml+
                    '                   </ul>'+
                    '               </div>'+
                    '           </div>'+
                                    orderFooterHtml+
                    '       </div>'+
                    '   </div>'+
                    '</li>';
            }
            var $shtmlBox = $(UlHtml);
            _this.oSearchOrederList.append($shtmlBox);
            _this.oMoreBtnBox.show();

            $shtmlBox.find('.jsAddressTimer').each(function () {
                var $timerBox = $(this);
                _this.gitfOrderTimer($timerBox);
            });

            // 执行判断进哪个商详页
            _this.goToStoreEvent();

            lazLoading.DestroyLazLoadingImg();
            lazLoading.AddLazLoadingImg(_this.oSearchOrederList[0]);
        },

        // 倒计时
        gitfOrderTimer: function (timerBox) {
            var _this = this;
            console.log('timerBox.attr("data-timer")',timerBox.attr("data-timer"));
            var timerSecond = parseInt(timerBox.attr("data-timer"));
            var timerText = _this.formatTimer(timerSecond);
            timerBox.text(timerText);
            var tempTimerInterval = setInterval(function () {
                timerSecond -- ;
                var timerText = _this.formatTimer(timerSecond);
                timerBox.text(timerText);
                if(timerSecond <= 0){
                    clearInterval(tempTimerInterval);
                }
            },1000);
        },


        formatTimer: function (timerSecond) {
            var second =  timerSecond%60;
            var min = ((timerSecond - timerSecond%60)/60)%60;
            var honr = (timerSecond - timerSecond%3600)/3600;
            // console.log("%o  %o  %o  %o",timerSecond,honr,min,second);
            if(honr < 10){
                honr = "0" + honr;
            }
            if(min < 10){
                min = "0" + min;
            }
            if(second < 10){
                second = "0" + second;
            }
            var timerText = honr + ":" + min+":"+second;
            return timerText;
        },


        // 判断是进入海外店铺还是进入普通店铺的接口
        goToStoreDetail: function (supplierId) {
            var _this = this;
            G_JSON_POST(storeDetailUrl,{'supplierId':supplierId},function (data) {
                var _data = data.data;
                var _ret = data.ret;
                // console.log('data',_data,_ret);
                if(_ret.code=='0'){
                    if(_data){
                        // 海外馆商家
                        window.location.href =  BASE_URL +'/h/store/storehome?supplierId='+ supplierId ;
                    }
                    else{
                        // 普通商家
                        window.location.href =  BASE_URL +'/h/store/normalStore/'+ supplierId ;
                    }
                }
                else{
                    // 如果请求不到就跳转普通商家
                    window.location.href =  BASE_URL +'/h/store/normalStore/'+ supplierId ;
                }
            })
        },

        // 点击进入店铺详情页面要判断是否是海外店铺
        goToStoreEvent: function(){
            var _this = this;
            $('.js_goToStore').on('click',function () {
                var supplierId = $(this).attr('data-supplierId');
                _this.goToStoreDetail(supplierId);
            })
        }
    };
    // searchOrder.getSearchData();

    // 显示搜索页面
    oOrderSearchArea.on('click',function (e) {
        // console.log('123',nSildeWidth);
        oSlideSearchBox.show();
        bSearch = true;

        // 初始化一次即可
        if(isInit){
            // 初始化 获取节点等
            searchOrder.init();

            // 显示隐藏清空按钮以及点击清空按钮操作
            searchOrder.getInputData();
            // 滚动加载
            searchOrder.scrollData();
        }

        // 清空数据  如果有之前的数据未清空
        searchOrder.oSlideSearchText.val('');
        searchOrder.oSearchOrederList.html('');
        searchOrder.oMoreBtnBox.hide();
        searchOrder.oClearSearchBtn.hide();
        searchOrder.oNoOrder.hide();
        searchOrder.oHasSearchData.show();

        searchOrder.pagearr = 1;
        searchOrder.start = 0;


        oSlideSearchBox.stop().animate({left:0},300,function(){});

        isInit = false;
        e.stopPropagation();
    });

    // 回车键请求数据
    oSlideSearchBox.on('keydown',function (event) {
        // 页面在搜索区域的情况才能执行
        if(bSearch && event.keyCode == 13){
            // 搜索关键字
            searchWord = searchOrder.oSlideSearchText.val();
            if(searchWord != ''){
                // 清空之前搜索的数据  点取消的时候要不要清空数据
                searchOrder.oSearchOrederList.html('');
                searchOrder.oMoreBtnBox.hide();
                searchOrder.pagearr = 1;
                searchOrder.start = 0;
                // 失去焦点
                searchOrder.oSlideSearchText.blur();

                // 显示有数据页面
                searchOrder.oNoOrder.hide();
                searchOrder.oHasSearchData.show();
                // 再请求数据
                searchOrder.getSearchData(searchWord);
            }else{
                myPub.TipLayer('您未输入搜索内容哦~');
            }
        }else{
            // console.log('并不是回车键')
        }
    });

});